package com.rocksdata.mc.business;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.ctz.commonframe.utils.Logger;
import com.rocksdata.mc.BuildConfig;
import com.rocksdata.mc.entity.MyOAResponse;
import com.rocksdata.mc.entity.OAResponse;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.http.body.StringBody;
import org.xutils.x;

import java.math.BigInteger;

/**
 * Created by 陈堂正 on 2017/4/14.
 */

public class OAManager implements BusinessInterface.IOAManager{
    private static final String URL_GET_UNTREATED_OA_LIST = BuildConfig.OA_INTERFACE_HOST + "/OAService/GetAllUnfinishedWorks";
    private static final String URL_GET_TREATED_OA_LIST = BuildConfig.OA_INTERFACE_HOST + "/OAService/GetAllCompletedWorks";
    private static final String URL_GET_MY_OA_APPLY_LIST = BuildConfig.OA_INTERFACE_HOST + "/OAService/GetAllMyWorks";
    private static final String URL_GET_DELETE_OA_APPLY = BuildConfig.OA_INTERFACE_HOST + "/OAService/DestroyInstance";

    private static BusinessInterface.IOAManager instance = null;

    private OAManager(){}

    static synchronized BusinessInterface.IOAManager getInstance(){
        if(instance == null)
            instance = new OAManager();
        return instance;
    }

    @Override
    public void getUntreatedOAList(int page, final BusinessInterface.OnBusinessResultListener listener){
        RequestParams params = new RequestParams(URL_GET_UNTREATED_OA_LIST);
        try {
            JSONObject obj = new JSONObject();
            obj.put("UserID", UserInfoManager.getCurrentUserId());
            obj.put("PageIndex", page);
            obj.put("PageSize", 15);
            JSONObject paramJson = new JSONObject();
            paramJson.put("obj", obj.toString().replace("\"[", "[").replace("\\", "").replace("]\"", "]"));
            params.setAsJsonContent(true);
            StringBody body = new StringBody(paramJson.toString(), "utf-8");
            Logger.e("getUntreatedOAList url:" + URL_GET_UNTREATED_OA_LIST + ",body:" + paramJson.toString());
            params.setRequestBody(body);
        } catch (Exception e) {
            e.printStackTrace();
        }
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                Logger.e("getUntreatedOAList result:" + result);
                OAResponse response = JSON.parseObject(result, OAResponse.class);
                if(response == null){
                    Logger.e("getUntreatedOAList failure: parse json to object failure");
                    listener.onBusinessResult(false, null, null);
                }else{
                    if(response.isSuccess()){
                        listener.onBusinessResult(true, response.getRecordDetail().get(0).getDatas(), null);
                    }else{
                        Logger.e("getUntreatedOAList isSuccess=false:" + response.getRecordRemark());
                        listener.onBusinessResult(false, null, null);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Logger.e("getUntreatedOAList onError:" + ex.getLocalizedMessage());
                listener.onBusinessResult(false, null, null);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void getTreatedOAList(int page, final BusinessInterface.OnBusinessResultListener listener){
        RequestParams params = new RequestParams(URL_GET_TREATED_OA_LIST);
        try {
            JSONObject obj = new JSONObject();
            obj.put("UserID", UserInfoManager.getCurrentUserId());
            obj.put("PageIndex", page);
            obj.put("PageSize", 15);
            JSONObject paramJson = new JSONObject();
            paramJson.put("obj", obj.toString().replace("\"[", "[").replace("\\", "").replace("]\"", "]"));
            params.setAsJsonContent(true);
            StringBody body = new StringBody(paramJson.toString(), "utf-8");
            Logger.e("getTreatedOAList url:" + URL_GET_TREATED_OA_LIST + ",body:" + paramJson.toString());
            params.setRequestBody(body);
        } catch (Exception e) {
            e.printStackTrace();
        }
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                Logger.e("getTreatedOAList result:" + result);
                OAResponse response = JSON.parseObject(result, OAResponse.class);
                if(response == null){
                    Logger.e("getTreatedOAList failure: parse json to object failure");
                    listener.onBusinessResult(false, null, null);
                }else{
                    if(response.isSuccess()){
                        listener.onBusinessResult(true, response.getRecordDetail().get(0).getDatas(), null);
                    }else{
                        Logger.e("getTreatedOAList isSuccess=false:" + response.getRecordRemark());
                        listener.onBusinessResult(false, null, null);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Logger.e("getTreatedOAList onError:" + ex.getLocalizedMessage());
                listener.onBusinessResult(false, null, null);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void getMyOAApplyList(int page, final BusinessInterface.OnBusinessResultListener listener) {
        RequestParams params = new RequestParams(URL_GET_MY_OA_APPLY_LIST);
        try {
            JSONObject obj = new JSONObject();
            obj.put("UserID", UserInfoManager.getCurrentUserId());
            obj.put("PageIndex", page);
            obj.put("PageSize", 15);
            JSONObject paramJson = new JSONObject();
            paramJson.put("obj", obj.toString().replace("\"[", "[").replace("\\", "").replace("]\"", "]"));
            params.setAsJsonContent(true);
            StringBody body = new StringBody(paramJson.toString(), "utf-8");
            Logger.e("getMyOAApplyList url:" + URL_GET_MY_OA_APPLY_LIST + ",body:" + paramJson.toString());
            params.setRequestBody(body);
        } catch (Exception e) {
            e.printStackTrace();
        }
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                Logger.e("getMyOAApplyList result:" + result);
                MyOAResponse response = JSON.parseObject(result, MyOAResponse.class);
                if(response == null){
                    Logger.e("getMyOAApplyList failure: parse json to object failure");
                    listener.onBusinessResult(false, null, null);
                }else{
                    if(response.isSuccess()){
                        listener.onBusinessResult(true, response.getRecordDetail().get(0).getDatas(), null);
                    }else{
                        Logger.e("getMyOAApplyList isSuccess=false:" + response.getRecordRemark());
                        listener.onBusinessResult(false, null, null);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Logger.e("getMyOAApplyList onError:" + ex.getLocalizedMessage());
                listener.onBusinessResult(false, null, null);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void deleteOAApply(String id, final BusinessInterface.OnBusinessResultListener listener) {
        RequestParams params = new RequestParams(URL_GET_DELETE_OA_APPLY);
        try {
            JSONObject obj = new JSONObject();
            obj.put("RecordID", id);
            JSONObject paramJson = new JSONObject();
            paramJson.put("obj", obj.toString().replace("\"[", "[").replace("\\", "").replace("]\"", "]"));
            params.setAsJsonContent(true);
            StringBody body = new StringBody(paramJson.toString(), "utf-8");
            Logger.e("deleteOAApply url:" + URL_GET_DELETE_OA_APPLY + ",body:" + paramJson.toString());
            params.setRequestBody(body);
        } catch (Exception e) {
            e.printStackTrace();
        }
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                Logger.e("deleteOAApply result:" + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String status = jsonObject.getString("RecordStatus");
                    if ("1".equals(status)) {
                        listener.onBusinessResult(true, null, null);
                    } else {
                        String msg = jsonObject.optString("RecordRemark");
                        Logger.e("getMyOAApplyList isSuccess=false, msg:" + msg);
                        listener.onBusinessResult(false, null, null);
                    }
                } catch (JSONException e) {
                    Logger.e("deleteOAApply failure: parse json failure");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Logger.e("deleteOAApply onError:" + ex.getLocalizedMessage());
                listener.onBusinessResult(false, null, null);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

//    String.prototype.encrypt = function (pwd) {
//        var str = this;
//        //return str;
//        if (pwd == null || pwd.length <= 0) {
//            return str;
//            pwd = "www.PantoSoft.com";
//        }
//        var prand = "";
//        for (var i = 0; i < pwd.length; i++) {
//            prand += pwd.charCodeAt(i).toString();
//        }
//        var sPos = Math.floor(prand.length / 5);
//        var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) + prand.charAt(sPos * 4) + prand.charAt(sPos * 5));
//        var incr = Math.ceil(pwd.length / 2);
//        var modu = Math.pow(2, 31) - 1;
//        if (mult < 2) {
//            alert("加密失败,密码因子太简单,不能构建合适的哈希算法!");
//            return null;
//        }
//        var salt = Math.round(Math.random() * 1000000000) % 100000000;
//        prand += salt;
//        while (prand.length > 10) {
//            prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
//        }
//        prand = (mult * prand + incr) % modu;
//        var enc_chr = "";
//        var enc_str = "";
//        for (var i = 0; i < str.length; i++) {
//            enc_chr = parseInt(str.charCodeAt(i) ^ Math.floor((prand / modu) * 255));
//            if (enc_chr < 16) {
//                enc_str += "0" + enc_chr.toString(16);
//            } else enc_str += enc_chr.toString(16);
//            prand = (mult * prand + incr) % modu;
//        }
//        salt = salt.toString(16);
//        while (salt.length < 8) salt = "0" + salt;
//        enc_str += salt;
//        return enc_str;
//    }
    public static String encode (String src, String pwd) {
        if (TextUtils.isEmpty(src)) {
            return null;
        }
        if (TextUtils.isEmpty(pwd)) {
            return src;
        }
        String prand = "";
        for (int i = 0; i < pwd.length(); i++) {
            prand += pwd.codePointAt(i);
        }
        Logger.e("encode prand:" + prand);
        int sPos = prand.length() / 5;
        Logger.e("encode sPos:" + sPos);
        String multStr = String.valueOf(prand.charAt(sPos))
                + String.valueOf(prand.charAt(sPos * 2))
                + String.valueOf(prand.charAt(sPos * 3))
                + String.valueOf(prand.charAt(sPos * 4))
                + String.valueOf(prand.charAt(sPos * 5));
        int mult = Integer.parseInt(multStr);
        Logger.e("encode mult:" + mult);
        if (mult < 2) {
            Logger.e("加密失败,密码因子太简单,不能构建合适的哈希算法!");
            return null;
        }
        int incr = (int) Math.ceil(pwd.length() / 2.0f);
        Logger.e("encode incr:" + incr);
        long modu = (long) (Math.pow(2, 31) - 1);
        Logger.e("encode modu:" + modu);
        long salt = Math.round(0.1234567 * 1000000000) % 100000000;
        Logger.e("encode salt:" + salt);
        prand += salt;
        Logger.e("encode prand2:" + prand);
        while (prand.length() > 10) {
            String pre10Str = prand.substring(0, 10);
            Logger.e("encode 前10位：" + pre10Str);
            BigInteger pre10 = new BigInteger(pre10Str);
            String nextStr = prand.substring(10, prand.length());
            Logger.e("encode 剩下位：" + nextStr);
            BigInteger next = new BigInteger(nextStr);
            prand = pre10.add(next).toString();
            Logger.e("encode while循环prand:" + prand);
//            prand = (Integer.parseInt(prand.substring(0, 10)) + Integer.parseInt(prand.substring(10, prand.length()))) + "";
        }
        Logger.e("encode prand3:" + prand);
        long l1 = mult * new BigInteger(prand).longValue();
        Logger.e("encode l1:" + l1);
        long l2 = l1 + incr;
        Logger.e("encode l2:" + l2);
        prand = l2 % modu + "";
        Logger.e("encode prand4:" + prand);
        long enc_chr;
        String enc_str = "";
        for (int i = 0; i < src.length(); i++) {
            enc_chr = src.codePointAt(i) ^ (long)((Math.floor((Long.parseLong(prand) / modu) * 255)));
            if (enc_chr < 16) {
                enc_str += "0" + Long.toHexString(enc_chr);
            } else {
                enc_str += Long.toHexString(enc_chr);
            }
            prand = (mult * Integer.parseInt(prand) + incr) % modu + "";
        }
        Logger.e("enc_str:" + enc_str);
        String saltStr = Long.toHexString(salt);
        while (saltStr.length() < 8)
            saltStr = "0" + saltStr;
        Logger.e("salt2:" + saltStr);
        enc_str += saltStr;
        return enc_str;
    }
}
